package com.tanhua.server.serivce;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Sound;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.domain.vo.SoundVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.SoundApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class PeachBlossomService {

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Reference
    private SoundApi soundApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 接口名称：桃花传音-发送语音（学生实战）
     */
    public ResponseEntity<Object> sendVoice(MultipartFile soundFile) throws IOException {
        String key = "VOICE_SEND_" + UserHolder.getUserId();
        if ("0".equals(redisTemplate.opsForValue().get(key))) {
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("errCode", "10096");
            errorMap.put("errMessage", "次数已用完!");
            return ResponseEntity.status(500).body(errorMap);
        }
        String filename = soundFile.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = storageClient.uploadFile(
                soundFile.getInputStream(), soundFile.getSize(), suffix, null
        );
        String soundUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
        Sound sound = new Sound();
        sound.setUserId(UserHolder.getUserId());
        sound.setSoundUrl(soundUrl);
        if ("woman".equals(userInfoApi.findById(UserHolder.getUserId()).getGender())) {
            sound.setStatus(1);
        }
        soundApi.save(sound);
        if (redisTemplate.hasKey("VOICE_SEND_" + UserHolder.getUserId())) {
            String s = redisTemplate.opsForValue().get(key);
            Integer count = Integer.valueOf(s);
            count--;
            redisTemplate.opsForValue().set(key, String.valueOf(count), Duration.ofMillis(getNextDayMillis()));
        } else {
            redisTemplate.opsForValue().set(key, "9", Duration.ofMillis(getNextDayMillis()));
        }
        Map<String, String> map = new HashMap<>();
        map.put("errCode", "10099");
        map.put("errMessage", "发送成功！");
        return ResponseEntity.status(500).body(map);
    }


    /**
     * 接口名称：桃花传音-接收语音（学生实战）
     */
    public ResponseEntity<Object> receiveVoice() {
        Long userId = UserHolder.getUserId();
        String key = "VOICE_RECEIVE_" + userId;
        String countStr = redisTemplate.opsForValue().get(key);
        Integer count = 0;
        if (StringUtils.isEmpty(countStr)) {
            count = 9;
            redisTemplate.opsForValue().set(key, count.toString(), Duration.ofMillis(getNextDayMillis()));
        } else {
            count = Integer.valueOf(countStr);
        }
        if (count == 0) {
            Map<String, String> map = new HashMap<>();
            map.put("errCode", "10098");
            map.put("errMessage", "今日次数已用完!");
            map.put("remainingTimes", count.toString());
            return ResponseEntity.status(500).body(map);
        }
        String gender = userInfoApi.findById(userId).getGender();
        Sound sound = soundApi.findSound(userId, gender);
        if (sound == null) {
            Map<String, String> map = new HashMap<>();
            map.put("errCode", "10097");
            map.put("errMessage", "暂无语音消息");
            return ResponseEntity.status(500).body(map);
        }
        UserInfo userInfo = userInfoApi.findById(sound.getUserId());
        SoundVo vo = new SoundVo();
        vo.setId(sound.getUserId());
        vo.setAvatar(userInfo.getAvatar());
        vo.setNickname(userInfo.getNickname());
        vo.setGender(userInfo.getGender());
        vo.setAge(userInfo.getAge());
        vo.setSoundUrl(sound.getSoundUrl());
        vo.setRemainingTimes(count);
        redisTemplate.opsForValue().set(key, String.valueOf(count - 1), Duration.ofMillis(getNextDayMillis()));
        return ResponseEntity.ok(vo);
    }


    /**
     * 获取次日00:00时间
     *
     * @return
     */
    public static Long getNextDayMillis() {
        Calendar ca = Calendar.getInstance();
        ca.set(Calendar.HOUR_OF_DAY, 0);
        ca.set(Calendar.MINUTE, 0);
        ca.set(Calendar.SECOND, 0);
        ca.set(Calendar.MILLISECOND, 0);
        ca.add(Calendar.DAY_OF_MONTH, 1);
        return ca.getTimeInMillis() - System.currentTimeMillis();
    }
}
